package br.ita.redecasd.mi.ws;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.sql.SQLException;

import javax.naming.NamingException;

import br.ita.redecasd.mi.auth.SignValidator;
import br.ita.redecasd.mi.db.Session;
import br.ita.redecasd.mi.ldap.LDAPManager;

public class SessionHandlerWS {
	
	public boolean validateSession(String userAgent, String username)  {
		try
        {
			return Session.getInstance().validateSession(userAgent);
            
        }
        catch( Exception e )
        {
            return false;
        }
    }
	
	public String validateSign( String username, String userAgent, byte[] signature ) throws InvalidKeyException, FileNotFoundException, CertificateException, NoSuchAlgorithmException, SignatureException, IOException, NamingException
	{
		boolean validated = SignValidator.validateSignature(username, userAgent, signature);
	    if ( validated  )
	    {
	        try
	        {
	        	String sessionID = username + userAgent;
	            Session.getInstance().createSession(sessionID);
	            return sessionID;
	        }
	        catch ( Exception sqle )
	        {
	        }
	                
	    }
	    
	    return null;
	}
	
	public String[] getPatientDetails( String login ) throws NamingException
	{
		LDAPManager ldap = new LDAPManager();
		return ldap.getPatientDetails(login);
	}
	
	public boolean mustAuthenticate(String medLogin, String patientLogin) throws ClassNotFoundException
	{
		try {
			return Session.getInstance().physistCanGetPatientDetails(medLogin, patientLogin);
		} catch (SQLException e) {
			// TODO Bloco catch gerado automaticamente
			e.printStackTrace();
			return true;
		}
	}
	
	public void updateACL(String medLogin, String patientLogin ) throws  ClassNotFoundException
	{
		try {
			Session.getInstance().giveMedAccessToPatientsRecords(medLogin, patientLogin );
		} catch (SQLException e) {
			// TODO Bloco catch gerado automaticamente
			e.printStackTrace();
		}
	}
	
	
}



